import axios from "axios";

// 使用当前的MySQL后端配置，端口可能是8080或配置的其他端口
const API_BASE_URL = "http://localhost:8080/api";

export const checkHealth = async () => {
  try {
    // 设置超时时间为3秒，避免长时间等待
    const response = await axios.get(`${API_BASE_URL}/health`, {
      timeout: 3000,
      // 允许发送跨域凭证
      withCredentials: true,
    });
    console.log("健康检查响应:", response.data);
    return response.data;
  } catch (error) {
    console.error("健康检查失败:", error.message);
    if (error.response) {
      // 服务器响应了，但状态码不在 2xx 范围内
      console.error("响应状态:", error.response.status);
      console.error("响应数据:", error.response.data);
    } else if (error.request) {
      // 请求已发送但没有收到响应
      console.error("未收到响应，可能是CORS问题或服务未启动");
    }
    throw error;
  }
};

export const fetchTemplates = async () => {
  const response = await axios.get(`${API_BASE_URL}/templates`);
  return response.data;
};

export const fetchPopularMemes = async () => {
  const response = await axios.get(`${API_BASE_URL}/memes/popular`);
  return response.data.content || response.data;
};

export const generateMeme = async (formData) => {
  const response = await axios.post(`${API_BASE_URL}/memes`, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
  return response.data;
};

export const generateGifFromServer = async (formData) => {
  try {
    const response = await axios.post(
      `${API_BASE_URL}/memes/generate-multi-text-gif`,
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
        responseType: "blob", // 指定响应类型为blob
      }
    );

    // 创建Blob URL
    const gifUrl = URL.createObjectURL(response.data);
    console.log("GIF生成成功，URL:", gifUrl);

    // 返回包含URL的对象
    return { gifUrl };
  } catch (error) {
    console.error("生成GIF失败:", error);
    throw error;
  }
};

export const shareMeme = async (memeId) => {
  const response = await axios.post(`${API_BASE_URL}/memes/${memeId}/share`);
  return response.data;
};
